package com.liseen.loader
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.utils.ByteArray;
	/**
	 * XML加载器
	 * @author Liseen
	 * 
	 */	
	public class XMLLoadItem extends LoadItem
	{
		public var loader:URLLoader;
		public function XMLLoadItem(url:String, type:String)
		{
			if(url.indexOf("?")==-1)
			{
				url = url+"?v="+Math.random().toString();
			}
			
			super(url, type);
		}
		
		override public function onErrorHandler(event:ErrorEvent):void
		{
			super.onErrorHandler(event);
		}
		
		override public function stop():void
		{
			try
			{
				if (loader)
				{
					loader.close();
				}
			}
			catch(e:Error)
			{
			}
			super.stop();
		}
		
		override public function onCompleteHandler(event:Event):void
		{
			try
			{
				if(loader.data is ByteArray)
				{
					if(ByteArray(loader.data)[0]==120)
					{
						ByteArray(loader.data).uncompress();
					}
					
					content = new XML(loader.data);
				}
			}catch(error:Error)
			{
				content = null;
			}
			super.onCompleteHandler(event);
		}
		
		override public function load():void
		{
			loader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(Event.OPEN,onStartedHandler,false,0,true);
			loader.addEventListener(ProgressEvent.PROGRESS,onProgressHandler,false,0,true);
			loader.addEventListener(Event.COMPLETE,onCompleteHandler,false,0,true);
			loader.addEventListener(IOErrorEvent.IO_ERROR,onErrorHandler,false,0,true);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,super.onHttpStatusHandler,false,0,true);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,super.onSecurityErrorHandler,false,0,true);
			try
			{
				loader.load(urlRequest);
			}catch(e:SecurityError){
			
			}
			
		}
		
		
		override protected function cleanListeners():void
		{
			if (loader)
			{
				loader.removeEventListener(ProgressEvent.PROGRESS, onProgressHandler, false);
				loader.removeEventListener(Event.COMPLETE, onCompleteHandler, false);
				loader.removeEventListener(IOErrorEvent.IO_ERROR, onErrorHandler, false);
				loader.removeEventListener(Event.OPEN, onStartedHandler, false);
				loader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, super.onHttpStatusHandler, false);
				loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, super.onSecurityErrorHandler, false);
			}
		}
		
		override public function destroy():void
		{
			stop();
			cleanListeners();
			content = null;
			loader = null;
		}
		
		
	}
}